<?php

namespace App\Controller\Backend\Division;

use App\Constants\Division;
use App\Controller\AbstractController;
use App\Repository\Contro\DivisionContro;
use App\Service\System\Tree;
use Hyperf\Di\Annotation\Inject;

class DivisionController extends AbstractController
{
    #[Inject]
    public DivisionContro $divisionContro;

    public function getDivision(){
        $res = $this->divisionContro->getDivisions();
        $res = array_map(function($re) {
            $re['division_type'] = match ($re['division_type']) {
                Division::COMPANY->value => strtolower(Division::COMPANY->name),
                Division::GROUP->value =>  strtolower(Division::GROUP->name),
            };
            return $re;
        }, $res);
        $data = categorizeArray($res,'division_type');
        $tree = new Tree('id','parent_id','children');
        foreach($data as $key => $datum){
            $tree->load($datum);
            $data[$key] = $tree->DeepTree();
        }
        return success($data);
    }

    public function addDivision(){
        $data = [
            'division_name' => $this->request->post('division_name',''),
            'division_type' => $this->request->post('division_type',1),
            'parent_id' => $this->request->post('parent_id',0),
        ];
        $validator = $this->validationFactory->make(
            [
                'division_name' => $data['division_name'],
                'division_type' => $data['division_type'],
                'parent_id' => $data['parent_id'],
            ],
            [
                'division_name' => 'required',
                'division_type' => 'required|in:1,2',
            ],
            [
                'division_name.required' => '组织名称不能为空',
                'division_type.required' => '组织类型不能为空',
                'division_type.in' => '组织类型必须正确',
            ]
        );
        if ($validator->fails()){
            apiError($validator->errors()->first());
        }

        $res = $this->divisionContro->addDivisions($data);
        return success($res);
    }

}